package com.itheima.pinda.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class BaiDuApiUtils {

    private static final String ak = "LIOnvWxLn85bqkCRfLZHBbYYE9HoA9Ns";

    /**
     * 获取地址经纬度
     *
     * @param address 地址
     * @return
     */
    public static String getLngLat(String address){

        HashMap<String, String> params = new HashMap<>();
        params.put("address", address);
        params.put("output", "json");
        params.put("ak", ak);

        String url = "https://api.map.baidu.com/geocoding/v3/";

        String str = null;

        try {
            str = HttpUtils.sendHttpGet(url, params);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map map = JSON.parseObject(str, Map.class);
        Map result = (Map) map.get("result");
        Map location = (Map) result.get("location");

        String lng = new DecimalFormat("#.######").format(Double.parseDouble(location.get("lng").toString()));
        String lat = new DecimalFormat("#.######").format(Double.parseDouble(location.get("lat").toString()));


        return lat + "," + lng;
    }

    /**
     * 获取两点间的距离
     *
     * @param origin
     * @param destination
     * @return
     */
    public static String getDistance(String origin, String destination){

        HashMap<String, String> params = new HashMap<>();
        params.put("origin",origin);
        params.put("destination",destination);
        params.put("ak",ak);

        String url = "https://api.map.baidu.com/directionlite/v1/driving";

        String str = null;

        try {
            str = HttpUtils.sendHttpGet(url,params);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map map = JSON.parseObject(str, Map.class);
        Map result = (Map)map.get("result");
        JSONArray routes = JSON.parseArray(result.get("routes").toString());
        JSONObject jsonObject = (JSONObject) routes.get(0);
        String distance = jsonObject.get("distance").toString();

        return distance;
    }
}
